/**
 * 
 */
const WEBSOCKET_STATUS_OPEN = "open";
const WEBSOCKET_STATUS_ERROR = "error";
const WEBSOCKET_STATUS_CLOSE = "close";
const WEBSOCKET_MESSAGE_TYPE_INIT = "init";
const WEBSOCKET_MESSAGE_TYPE_UPDATE = "update";
const WEBSOCKET_MESSAGE_TYPE_NEW = "new";

var curWwwPath = window.document.location.href;

//获取主机地址之后的目录如：/sxl/index.jsp
var pathName = window.document.location.pathname;
var pos = curWwwPath.indexOf(pathName);

//获取主机地址，如：localhost:8080
var basePath = curWwwPath.substring(curWwwPath.indexOf('://') + 3, pos);

//获取带"/"的项目名，如：/sxl
//var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1); 

var websocket;
var websocketStatus = null;

if ('WebSocket' in window) {
    websocket = new WebSocket("ws://" + basePath + projectName + "/chatroomSocketServer");
} else if ('MozWebSocket' in window) {
    websocket = new MozWebSocket("ws://" + projectName + "/chatroomSocketServer");
} else {
    websocket = new SockJS("http://" + basePath + projectName + "/sockjs/chatroomSocketServer");
}

websocket.onopen = function (evnt) {
	websocketStatus = WEBSOCKET_STATUS_OPEN;
};

websocket.onmessage = function (evnt) {
	var resultData = JSON.parse(evnt.data);
	var mType = resultData.mType;
	var chat = resultData.chat;
	if (typeof chat !== 'undefined' && chat != null) {
		var Gag = resultData.Gag;
		var liveRoomId = resultData.liveRoomId;
		var roleId = $("#roleId").val();
		if($("#practiceLessonIdValue").val() && $("#practiceLessonIdValue").val() == liveRoomId){
			$('#liveTalk').val(Gag);
			if(roleId != 0){
			ueController(Gag);
			}else if(roleId == 0){
			ueControllerRoleId(Gag);
			}
		}
		
	}
	if (typeof mType !== 'undefined' && mType != null) {
		if(mType == "viewers"){
			//alert(practiceLessonId+","+resultData.practiceLessonId+","+(practiceLessonId == resultData.practiceLessonId));
			if(practiceLessonId == resultData.practiceLessonId){
				$("#showViewers").html('<i class="fa fa-eye" aria-hidden="true"></i>&nbsp;&nbsp;'+resultData.mValue);
				
			}
			return;
		}
		var mValue = resultData.mValue;
		var time = resultData.time;
		var name = resultData.name;
		var id = resultData.id;
		var roleId = resultData.roleId;
		var StringHtml = "";
		var userId = $("#userId").val();
		var indexId = $("#roleId").val();
		var TalkStop = "";
		if(roleId != 0 ){
			/*TalkStop +='    <a style="color:red;cursor:pointer;" class="stop">禁言</a>';*/
		}else if(roleId == 0){
			TalkStop = "";
		}
		var authorName = mValue.substring(mValue.lastIndexOf("[author]:")+9);
		 mValue=mValue.substring(0,mValue.lastIndexOf("[author]:"));
	if(mValue == ""){
		mValue = " ";
	}
		
		if($("#userName").val() == authorName){
			//自己发送的文字
			if(userId == id){
				StringHtml += ' <div id="messageOutside" class="messageOutside"> ';
				StringHtml += ' 	<div id="messageCenter" class="messageCenter"> ';
				StringHtml += ' 		<div id="messageTopOwn" class="messageTopOwn"  style="text-align:right;">'+name+'['+time+']';
				StringHtml += ' 		</div> ';
				StringHtml += ' 		<div id="messageLowerOwn" class="messageLowerOwn"> ';
				StringHtml += ' 			<div class="right-wechat-div"><span class="right-wechat-span">'+mValue+'</span></div> ';
				StringHtml += ' 		</div> ';
				StringHtml += ' 	</div> ';
				StringHtml += ' 	<div style="clear:both"></div> ';
				StringHtml += ' </div> ';
			}else{
				if(indexId != 0){
				StringHtml += ' <div id="messageOutside" class="messageOutside" style="display:inline"> ';
				StringHtml += ' 	<div id="messageCenter" class="messageCenter"> ';
				StringHtml += ' 		<div id="messageTop" class="messageTop" style="text-align:right;">'+name+'['+time+']';
				StringHtml += ' 		</div> ';
				StringHtml += ' 		<div id="messageLower" class="messageLower"> ';
				StringHtml += ' 			<div class="right-wechat-div"><span class="right-wechat-span">'+mValue+'</span></div> ';
				StringHtml += ' 		</div> ';
				StringHtml += ' 	</div> ';
				StringHtml += ' 	<div style="clear:both"></div> ';
				StringHtml += ' </div> ';
				}else if(indexId == 0){
					StringHtml += ' <div id="messageOutside" class="messageOutside" style="display:inline"> ';
					StringHtml += ' 	<div id="messageCenter" class="messageCenter"> ';
					StringHtml += ' 		<div id="messageTop" class="messageTop" style="text-align:right;">'+name+'['+time+']';
					StringHtml += TalkStop; 
					StringHtml += ' 		</div> ';
					StringHtml += ' 		<div id="messageLower" class="messageLower" > ';
					StringHtml += ' 			<div class="right-wechat-div"><span class="right-wechat-span">'+mValue+'</span></div> ';
					StringHtml += ' 		</div> ';
					StringHtml += ' 	</div> ';
					StringHtml += ' 	<div style="clear:both"></div> ';
					StringHtml += ' </div> ';
				}
			}
		}else{
			if(userId == id){
				StringHtml += ' <div id="messageOutside" class="messageOutside"> ';
				StringHtml += ' 	<div id="messageCenter" class="messageCenter"> ';
				StringHtml += ' 		<div id="messageTopOwn" class="messageTopOwn">'+name+'['+time+'] ';
				StringHtml += ' 		</div> ';
				StringHtml += ' 		<div id="messageLowerOwn" class="messageLowerOwn"> ';
				StringHtml += ' 			<div class="left-wechat-div"><span class="left-wechat-span">'+mValue+'</span></div> ';
				StringHtml += ' 		</div> ';
				StringHtml += ' 	</div> ';
				StringHtml += ' 	<div style="clear:both"></div> ';
				StringHtml += ' </div> ';
			}else{
				if(indexId != 0){
				StringHtml += ' <div id="messageOutside" class="messageOutside" style="display:inline"> ';
				StringHtml += ' 	<div id="messageCenter" class="messageCenter"> ';
				StringHtml += ' 		<div id="messageTop" class="messageTop">'+name+'['+time+'] ';
				StringHtml += ' 		</div> ';
				StringHtml += ' 		<div id="messageLower" class="messageLower"> ';
				StringHtml += ' 			<div class="left-wechat-div"><span class="left-wechat-span">'+mValue+'</span></div> ';
				StringHtml += ' 		</div> ';
				StringHtml += ' 	</div> ';
				StringHtml += ' 	<div style="clear:both"></div> ';
				StringHtml += ' </div> ';
				}else if(indexId == 0){
					StringHtml += ' <div id="messageOutside" class="messageOutside" style="display:inline"> ';
					StringHtml += ' 	<div id="messageCenter" class="messageCenter"> ';
					StringHtml += ' 		<div id="messageTop" class="messageTop">'+name+'['+time+'] ';
					StringHtml += TalkStop; 
					StringHtml += ' 		</div> ';
					StringHtml += ' 		<div id="messageLower" class="messageLower"> ';
					StringHtml += ' 			<div class="left-wechat-div"><span class="left-wechat-span">'+mValue+'</span></div> ';
					StringHtml += ' 		</div> ';
					StringHtml += ' 	</div> ';
					StringHtml += ' 	<div style="clear:both"></div> ';
					StringHtml += ' </div> ';
				}
			}
		}
		
		$("#messagePage").append(StringHtml);
		//触发禁言按钮
		/*$('.stop').on('click',function(){
			alert(1111);
		})*/
		if(roleId == 0){
			$("#messagePage2").append(StringHtml);
		}
		var div = document.getElementById('messagePage');
		div.scrollTop = div.scrollHeight;
		if (mType == WEBSOCKET_MESSAGE_TYPE_INIT || mType == WEBSOCKET_MESSAGE_TYPE_UPDATE) {
			if (mValue == 0) {
				hideMessage();
			} else {
				updateCountOfMessage(mValue);
			}
		} else if (mType == WEBSOCKET_MESSAGE_TYPE_NEW) {
			updateMessage();
			playMessageAudio();
			$.commonAlert.show({
				text: mValue,
				title: '消息提示',
				type: 'custom',
				class_name: 'gritter-success gritter-light',
				time: 5000
			});
		}
	}
	
};

websocket.onerror = function (evnt) {
	// TODO	error时处理
	websocketStatus = WEBSOCKET_STATUS_ERROR;
};

websocket.onclose = function (evnt) {
	// TODO	close时处理
	websocketStatus = WEBSOCKET_STATUS_CLOSE;
}

/**
 * 显示没有未读消息状态
 * @returns
 */
function hideMessage() {
	$('#count-of-message').hide();
	$('#notify-dropdown .fa-bell').removeClass('icon-animated-bell');
}

/**
 * 显示有未读消息状态
 * @returns
 */
function updateCountOfMessage(count) {
	$('#notify-dropdown .fa-bell').addClass('icon-animated-bell');
	$('#count-of-message').show();
	$('#count-of-message').text(count);
}

/**
 * 播放消息通知声音
 */
function playMessageAudio() {
	var audioStr = '';
	audioStr += '<audio id="notity-audio">';
	audioStr += '	<source src="' + projectName + '/static/audio/6918.mp3" type="audio/mp3">';
	audioStr += '</audio>';
	$('body').append(audioStr);
	$('#notity-audio')[0].play();
	//$('#notity-audio').remove();
}

function websocketDropdownToggle(_this, userId) {
	if (!$(_this).hasClass('open')) {
		$.ajax({
            url : projectName + '/sysUserNotification/listNotificationByNumber/' + userId,  
            type : "POST",  
            dataType: 'json',
            data : {
            	userId: userId,
            },  
            success : function(data) { 
            	var messageCount = data.countOfUnread;
            	var dropdownBody = '';
            	if (typeof data.notificationList !== 'undefined' && data.notificationList != null) {
            		dropdownBody = dropdownBodyHtml(data.notificationList);
            	}
            	if (messageCount == 0) {
    				hideMessage();
    			} else {
    				updateCountOfMessage(messageCount);
    			}
            	var dropdownHeader = dropdownHeaderHtml(messageCount);
        		var dropdownFooter = dropdownFooterHtml(userId);
        		$('#dropdown-menu').html(dropdownHeader + dropdownBody + dropdownFooter);
            }
        });
		
		$('#notify-dropdown').on('hide.bs.dropdown', function() {
			updateMessage();
		});
	}
}

function updateMessage() {
	var updateData = {
			mType: WEBSOCKET_MESSAGE_TYPE_UPDATE				
	};
	websocket.send(JSON.stringify(updateData));
}

function dropdownHeaderHtml(messageCount) {
	var headerHtml = '';	
	headerHtml += '<li class="dropdown-header">';
	headerHtml += '	<i class="ace-icon fa fa-exclamation-triangle"></i>';
	if (messageCount == 0) {
		headerHtml += '	<span id="dropdown-menu-count">没有未读消息</span>';
	} else {
		headerHtml += '	<span id="dropdown-menu-count">' + messageCount + ' 条消读消息</span>';
	}
	headerHtml += '</li><li class="divider"></li>';
	return headerHtml;
}

function dropdownBodyHtml(data) {
	var bodyHtml = '';	
	$(data).each(function(i, item) {
		bodyHtml += '<li  class="notify-container ' + (i == (data.length - 1) ? '' : 'notify-container-border') + '">';
		bodyHtml += '	<div class="clearfix">';
		bodyHtml += '		<span class="pull-left" style="padding:6px ;">' + item.message;
		bodyHtml += '		</span>';
		bodyHtml += '	</div>';
		bodyHtml += '</li><li class="divider"></li>';
	});
	return bodyHtml;
}

function dropdownFooterHtml(userId) {
	var footerHtml = '';
	var url = projectName + '/sys/sysuser/home#page/notification/' + userId;
	footerHtml += '<li class="dropdown-footer">';
	footerHtml += '	<a href="' + url + '" >';
	footerHtml += '		查看所有通知&nbsp; <i class="ace-icon fa fa-arrow-right"></i>';
	footerHtml += '	</a>';
	footerHtml += '</li>';
	return footerHtml;
}

function ueController(Gag){
	if(Gag == 1){
		UE.getEditor('message').setDisabled('fullscreen');
		$('.StopTalk').hide();
		$('.OpenTalk').show();
		$('#sendMessage').hide();
		$("#tishi").html("已被禁言");
		$("#lessonsendMessage").attr("disabled","disabled");
		$("#UserTalkTipSpan").html("全员禁言");
		if(livevideo){
			alert("你已被禁言");
		}
	}else if(Gag == 0){
		UE.getEditor('message').setEnabled();
		$('.OpenTalk').hide();
		$('.StopTalk').show();
		$('#sendMessage').show();
		$("#lessonsendMessage").removeAttr("disabled");
		$("#tishi").html("请按Enter发送信息");
		$("#UserTalkTipSpan").html("全员发言");
	}
}

function ueControllerRoleId(Gag){
	if(Gag == 1){
		$('.StopTalk').hide();
		$('.OpenTalk').show();

		$("#TalkTipSpan").html("解除禁言");
		$("#talkSwitch").addClass("layui-form-onswitch");
		
	}else if(Gag == 0){
		$('.OpenTalk').hide();
		$('.StopTalk').show();
		$("#TalkTipSpan").html("全员禁言");
		$("#talkSwitch").removeClass("layui-form-onswitch");
	}
}
